<?php
require('jsonencode.php');
require('OModel.php');
// Get the requested page. By default grid sets this to 1. 
$page = $_GET['page'];
// get how many rows we want to have into the grid - rowNum parameter in the grid 
$limit = $_GET['rows'];
// get index row - i.e. user click to sort. At first time sortname parameter -
// after that the index from colModel 
$sidx = $_GET['sidx'];
// if we not pass at first time index use the first column for the index or what you want
if(!$sidx) $sidx =1;
//
$sord = $_GET['sord']; // get the direction 
//
$link = DBOpen();
$db_selected = mysql_select_db("calcwb",$link);
// calculate the number of rows for the query. We need this for paging the result 
$result = mysql_query("SELECT COUNT(*) AS count FROM logbook"); 
$row = mysql_fetch_array($result,MYSQL_ASSOC); 
$count = $row['count'];
// calculate the total pages for the query 
if( $count > 0 && $limit > 0) { 
              $total_pages = ceil($count/$limit); 
} else { 
              $total_pages = 0; 
} 
 
// if for some reasons the requested page is greater than the total 
// set the requested page to total page 
if ($page > $total_pages) $page=$total_pages;
 
// calculate the starting position of the rows 
$start = $limit*$page - $limit;
 
// if for some reasons start position is negative set it to 0 
// typical case is that the user type 0 for the requested page 
if($start <0) $start = 0; 
// DATE_FORMAT(FlightDate,'%m/%d/%Y') AS FD
$sql = "SELECT logbook.LogID, FlightDate AS FD, logbook.FromID, logbook.ToID, logbook.Comment, ";
$sql = $sql . "logbook.InstrumentApproach, logbook.Landings, aircraft.NNumber, make.Name AS MakeName, category.Name AS CatName, "; 
$sql = $sql . "AirFrom.Ident AS IdentFrom, AirTo.Ident AS IdentTo ";
$sql = $sql . "FROM logbook ";
$sql = $sql . "LEFT JOIN aircraft ON aircraft.AircraftID = logbook.AircraftID ";
$sql = $sql . "INNER JOIN make ON make.MakeID=aircraft.MakeID ";
$sql = $sql . "INNER JOIN category ON category.CategoryID=make.CategoryID ";
$sql = $sql . "INNER JOIN airport as AirFrom ON AirFrom.AirportID=logbook.FromID ";
$sql = $sql . "INNER JOIN airport as AirTo ON AirTo.AirportID=logbook.ToID ";
$sql = $sql . "ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query($sql) or die(mysql_error());
$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 
$i=0; 
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) 
{ 
        $date = strtotime($row['FD']);
        $dout = strftime("%d/%m/%Y" , $date);
	$responce->rows[$i]['id']=$row['LogID']; 
	$responce->rows[$i]['cell']=array(
		$row['LogID'],
		$dout, 
		$row['MakeName'],
		$row['NNumber'],
		$row['IdentFrom'],
		$row['IdentTo'],
		$row['Comment'],
		$row['InstrumentApproach'],
		$row['Landings']); 
	$i++; 
} 
mysql_close($link);
echo json_encode($responce); 
?>